//
//  LEEPictureCollectionController.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/22.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit


let colCount: CGFloat = 3
let PhotoMargin: CGFloat = 4
let cellWidth: CGFloat = (kUISCRRENW - (colCount + 1) * PhotoMargin) / colCount
//限定照片上传数量
let photoCount: Int = 9


private let reuseIdentifier = "Cell"

class LEEPictureCollectionController: UICollectionViewController {

    lazy var chooseImages: [UIImage] = [UIImage]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(LEEPhotoCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        self.collectionView?.backgroundColor = UIColor.white
    }
    

    // MARK: UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        let  count = (self.chooseImages.count == photoCount ? 0 : 1)
        
        return self.chooseImages.count + count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LEEPhotoCell
    
        cell.backgroundColor = arcColor()
        
        if self.chooseImages.count == indexPath.item {
            
            cell.photo = nil
        }else{
            
            cell.photo = chooseImages[indexPath.item]
        }
    
        cell.delegate = self
        
        return cell
    }
    
    func moveToPhotoLibrary() {
    
        let imagePicker = UIImagePickerController()
        
        imagePicker.delegate = self
        self.present(imagePicker, animated: true, completion: nil)
        
    }
    
}

extension LEEPictureCollectionController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
//        print(info)
        let img = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        chooseImages.append(img.scale(width: kUISCRRENW))
        
        self.collectionView?.reloadData()
        
        dismiss(animated: true, completion: nil)
    }

}


extension LEEPictureCollectionController: LEEPhotoCellDelegate {

    func clickPicAddBotton(cell: LEEPhotoCell) {
        print("增加")
        moveToPhotoLibrary()
    }
    
    func clickDeleteBotton(cell: LEEPhotoCell) {
        print("删除")
        guard let index = collectionView?.indexPath(for: cell) else {return}

        chooseImages.remove(at: index.item)
        
        collectionView?.reloadData()
        
         //没有图片的时候就隐藏图片视图
        self.view.isHidden = chooseImages.count == 0
    }

    
}


@objc protocol LEEPhotoCellDelegate: NSObjectProtocol {

    @objc optional func clickPicAddBotton(cell: LEEPhotoCell)
    
    @objc optional func clickDeleteBotton(cell: LEEPhotoCell)
}

// MARK: 自定义cell
class LEEPhotoCell: UICollectionViewCell {
    
    //添加图片按钮点击
    @objc private func clickPicAdd() {
    
        if photo != nil {
            print("已经有图片了")
            return
        }
        
        delegate?.clickPicAddBotton?(cell: self)
    }
    //移除图片按钮点击
    @objc private func clickDeleteBtn() {
    
        delegate?.clickDeleteBotton?(cell: self)
    }

    var photo: UIImage? {
        
        didSet{
        
            picAdd.setImage(photo, for: .normal)
            
            deleteBtn.isHidden = photo == nil
        }
    }
    
    weak var delegate: LEEPhotoCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // UI搭建
    private func setupUI() {
    
        self.contentView.addSubview(picAdd)
        self.contentView.addSubview(deleteBtn)
        
        picAdd.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self)
        }
        deleteBtn.snp.makeConstraints { (make) in
            
            make.top.right.equalTo(self)
        }
    }

    //增加按钮
    lazy var picAdd: UIButton = {
        let addBtn = UIButton()
       
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .highlighted)
        
        addBtn.imageView?.contentMode = .scaleAspectFill
        
        addBtn.addTarget(self, action: #selector(clickPicAdd), for: .touchUpInside)
        return addBtn
    }()
    
    //删除按钮
    lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        btn.sizeToFit()
        
        btn.addTarget(self, action: #selector(clickDeleteBtn), for: .touchUpInside)
        return btn
    }()
}













